<template>
  <div class="upload">
    <el-card>
      <h3 style="text-align: center">{{ $route.query.name }}导入</h3>
      <excel-upload :before-upload="beforeUpload" :on-success="onSuccess" />
    </el-card>
  </div>
</template>

<script>
import { sysUserBatch } from '@/api/employees'
export default {
  methods: {
    beforeUpload(file) {
      console.log(file)
      return true
    },
    async onSuccess({ header, results }) {
      // 定义数据格式
      const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      // 遍历数组,转化数据格式
      const arr = results.map((val) => {
        const newObj = {}
        Object.keys(val).forEach((item) => {
          newObj[obj[item]] = val[item]
          if (obj[item] === 'timeOfEntry' || obj[item] === 'correctionTime') {
            // 如果包含时间 , 转化时间格式
            newObj[obj[item]] = this.changeDate(val[item])
          }
        })
        return newObj
      })
      // 导入接口
      await sysUserBatch(arr)
      this.$message.success('导入成功')
      this.$router.push('/employees')
      console.log(header, results, arr)
    },
    // 转化时间方法
    changeDate(num) {
      const t = new Date(((num - 1) * 24 - 8) * 60 * 60 * 1000)
      t.setYear(t.getFullYear() - 70)
      return t
    }
  }
}
</script>

<style lang="scss" scoped>
.upload {
  padding: 15px;
}
</style>
